package com.capinfo.commons.project.utils;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import java.sql.Timestamp;
import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;

import com.capinfo.framework.model.BaseEntity;
import com.capinfo.framework.util.LogUtils;
import com.capinfo.framework.util.PropertyUtils;

/**
 * Created by Administrator on 2017/10/10.
 */
public class JsonUtils {
	
	private static final Log logger = LogFactory.getLog(JsonUtils.class);
	
	private static JsonConfig buildJsonConfig() {

		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
		jsonConfig.registerJsonValueProcessor(Timestamp.class, new JsonDateValueProcessor());
		
		return jsonConfig;
	}

	public static JSONObject toGlobleJsonObject(Object object) {

		return toJson(object);
	}

	public static JSONObject toJson(Object object, String... exclusions) {
		
		JSONObject json = new JSONObject();

		json = json.fromObject(object, buildJsonConfig());
		for (String exclusion : exclusions) {

			json.remove(exclusion);
		}
		
		return json;
	}

	public static JSONObject toJson4Entity(BaseEntity source, String... ignoreProperties) {

		Object target = null;
		try {
			target = source.getClass().newInstance();
		} catch (InstantiationException | IllegalAccessException e) {
			
			LogUtils.debugException(logger, e);
		}

		JSONObject json = new JSONObject();
		if( null == target ) {
			
			return json;
		}
		
		BeanUtils.copyProperties(source, target, ignoreProperties);
		
		return json.fromObject(target, buildJsonConfig());
	}

	public static JSONObject toJson4EntityByProperties(BaseEntity source, String... properties) {

		Object target = null;
		try {
			target = source.getClass().newInstance();
		} catch (InstantiationException | IllegalAccessException e) {
			
			LogUtils.debugException(logger, e);
		}
		
		JSONObject json = new JSONObject();
		if( null == target ) {
			
			return json;
		}
		
		for( String property: properties ) {
			
			PropertyUtils.setProperty(target, property, PropertyUtils.getProperty(source, property));
		}

		return json.fromObject(target, buildJsonConfig());
	}
}
